Page({
  data: {
    activeTab: 0,
    tabs: [
      { label: '全部', value: 0 },
      { label: '待付款', value: 1 },
      { label: '进行中', value: 2 },
      { label: '已完成', value: 3 },
      { label: '已取消', value: 4 }
    ],
    loading: true,
    orderList: []
  },

  onLoad() {
    // 加载订单列表数据
    this.loadOrderList()
  },

  // 加载订单列表数据
  loadOrderList() {
    this.setData({ loading: true })
    
    // 模拟数据，实际项目中应该从云数据库获取
    setTimeout(() => {
      const mockData = [
        {
          _id: 'order001',
          serviceName: '专业护理服务',
          serviceTime: '2025-09-23 09:00',
          totalPrice: 150,
          status: 'pending_payment',
          hasReviewed: false
        },
        {
          _id: 'order002',
          serviceName: '老年人康复训练',
          serviceTime: '2025-09-24 10:00',
          totalPrice: 200,
          status: 'paid',
          hasReviewed: false
        },
        {
          _id: 'order003',
          serviceName: '营养餐配送',
          serviceTime: '2025-09-22 12:00',
          totalPrice: 50,
          status: 'completed',
          hasReviewed: true
        },
        {
          _id: 'order004',
          serviceName: '日常生活照料',
          serviceTime: '2025-09-25 14:00',
          totalPrice: 120,
          status: 'in_progress',
          hasReviewed: false
        },
        {
          _id: 'order005',
          serviceName: '老年心理咨询',
          serviceTime: '2025-09-20 15:00',
          totalPrice: 180,
          status: 'completed',
          hasReviewed: false
        }
      ]
      
      // 根据当前标签页筛选数据
      let filteredList = mockData
      if (this.data.activeTab !== 0) {
        const statusMap = {
          1: 'pending_payment',
          2: 'in_progress',
          3: 'completed',
          4: 'cancelled'
        }
        const status = statusMap[this.data.activeTab]
        filteredList = mockData.filter(item => item.status === status)
      }
      
      this.setData({
        orderList: filteredList,
        loading: false
      })
    }, 500)
    
    // 实际项目中的云数据库查询示例
    /*
    const db = wx.cloud.database()
    const _ = db.command
    
    // 构建查询条件
    let query = {}
    
    // 根据标签页筛选状态
    if (this.data.activeTab !== 0) {
      const statusMap = {
        1: 'pending_payment',
        2: 'in_progress',
        3: 'completed',
        4: 'cancelled'
      }
      query.status = statusMap[this.data.activeTab]
    }
    
    db.collection('orders')
      .where(query)
      .orderBy('createTime', 'desc')
      .get()
      .then(res => {
        this.setData({
          orderList: res.data,
          loading: false
        })
      })
      .catch(err => {
        console.error('查询订单列表失败', err)
        this.setData({ loading: false })
        wx.showToast({
          title: '加载失败，请重试',
          icon: 'none'
        })
      })
    */
  },

  // 标签页切换事件
  onTabsChange(e) {
    this.setData({
      activeTab: e.detail.value
    })
    this.loadOrderList()
  },

  // 获取状态文本
  getStatusText(status) {
    const statusMap = {
      'pending_payment': '待付款',
      'paid': '已支付',
      'in_progress': '进行中',
      'completed': '已完成',
      'cancelled': '已取消'
    }
    return statusMap[status] || status
  },

  // 获取状态颜色
  getStatusColor(status) {
    const colorMap = {
      'pending_payment': '#FF9D4C',
      'paid': '#4080FF',
      'in_progress': '#4080FF',
      'completed': '#07C160',
      'cancelled': '#888888'
    }
    return colorMap[status] || '#333333'
  },

  // 支付订单
  onPayOrder(e) {
    const orderId = e.currentTarget.dataset.id
    wx.navigateTo({
      url: `/pages/order/payment?id=${orderId}`
    })
  },

  // 取消订单
  onCancelOrder(e) {
    const orderId = e.currentTarget.dataset.id
    wx.showModal({
      title: '取消订单',
      content: '确定要取消该订单吗？',
      confirmText: '确定取消',
      confirmColor: '#FF0000',
      success: (res) => {
        if (res.confirm) {
          wx.showLoading({
            title: '处理中...',
          })
          
          // 模拟取消订单，实际项目中应该调用云函数
          setTimeout(() => {
            wx.hideLoading()
            wx.showToast({
              title: '订单已取消',
              icon: 'success'
            })
            
            // 刷新订单列表
            this.loadOrderList()
          }, 1000)
          
          // 实际项目中的云函数调用示例
          /*
          wx.cloud.callFunction({
            name: 'cancelOrder',
            data: { orderId },
            success: () => {
              wx.hideLoading()
              wx.showToast({
                title: '订单已取消',
                icon: 'success'
              })
              this.loadOrderList()
            },
            fail: (err) => {
              wx.hideLoading()
              console.error('取消订单失败', err)
              wx.showToast({
                title: '取消失败，请重试',
                icon: 'none'
              })
            }
          })
          */
        }
      }
    })
  },

  // 评价订单
  onReviewOrder(e) {
    const orderId = e.currentTarget.dataset.id
    wx.navigateTo({
      url: `/pages/review/create?orderId=${orderId}`
    })
  },

  // 查看订单详情
  onViewOrder(e) {
    const orderId = e.currentTarget.dataset.id
    wx.navigateTo({
      url: `/pages/order/detail?id=${orderId}`
    })
  },

  // 下拉刷新
  onPullDownRefresh() {
    this.loadOrderList()
    wx.stopPullDownRefresh()
  },

  // 触底加载更多
  onReachBottom() {
    // 实际项目中可以在这里实现分页加载
    // this.loadMoreOrders()
  }
})